package com.filestation.backend.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;

@Slf4j
public class ZipUtils {

    /**
     * 将多个文件压缩为一个zip文件
     * @param files 文件列表
     * @param zipFileName zip文件名
     * @return 压缩后的文件
     */
    public static File compressToZip(List<MultipartFile> files, String zipFileName) throws IOException {
        File zipFile = new File(System.getProperty("java.io.tmpdir"), zipFileName);
        
        try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(new FileOutputStream(zipFile))) {
            for (MultipartFile file : files) {
                String fileName = file.getOriginalFilename();
                if (fileName == null || fileName.trim().isEmpty()) {
                    fileName = "未命名文件" + System.currentTimeMillis();
                }
                
                ZipArchiveEntry zipEntry = new ZipArchiveEntry(fileName);
                zipOut.putArchiveEntry(zipEntry);
                
                try (InputStream inputStream = file.getInputStream()) {
                    IOUtils.copy(inputStream, zipOut);
                }
                
                zipOut.closeArchiveEntry();
            }
            zipOut.finish();
        } catch (IOException e) {
            log.error("压缩文件失败", e);
            throw e;
        }
        
        return zipFile;
    }
} 